package taskasync;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;


import android.app.ProgressDialog;
import android.os.AsyncTask;

public class InserirNovoJogadorTask extends AsyncTask<String, Integer, String>
{
	private ProgressDialog caixaDeProgresso;
	private String RespostaDoServidor;
	
	@Override
	protected String doInBackground(String... nomeUsuario) 
	{
		try
		{
			System.out.println("doInBackGroundEhExecutado");
			InetAddress serverAddr = InetAddress.getByName("10.0.2.2");
			Socket socketComunicaComServidor = new Socket(serverAddr,12345);
			String mensagemEntrarNovoUsuario = "join " + nomeUsuario[0];
			OutputStream outPutStream = socketComunicaComServidor.getOutputStream();
			PrintWriter printWriter = new PrintWriter(outPutStream);
			
			printWriter.println(mensagemEntrarNovoUsuario);
			printWriter.flush();
			//printWriter.close();
			//outPutStream.close();
			InputStream inputStream = socketComunicaComServidor.getInputStream();
			BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
			
			
			//InputStream inputStream = socketComunicaComServidor.getInputStream();
			String retornoDoServidor = buffer.readLine();
			
			
			//buffer.close();
			//inputStream.close();
			socketComunicaComServidor.close();
			
			
			return retornoDoServidor;
		}
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			System.out.println(e);
			e.printStackTrace();
	    	return e.getMessage();
		} 
	}
	
	public void setCaixaDeProgresso(ProgressDialog caixaDeProgresso)
	{
		this.caixaDeProgresso = caixaDeProgresso;
	}
	
	public void setRespostaDoServidor(String respostaDoServidor)
	{
		this.RespostaDoServidor = respostaDoServidor;
	}
	
	@Override
	protected void onPostExecute(String retornoDoServidor) 
	{
		if(retornoDoServidor == null)
		{
			this.RespostaDoServidor = "falha na comunicacao";
		}
		else
		{
			this.caixaDeProgresso.dismiss();
			this.RespostaDoServidor = retornoDoServidor;
		}
	}
	
}
